package com.sen.gateway.filter;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 请求统计分析埋点过滤器
 * @author esjiang
 */
@Component
@Slf4j
public class RequestStatisticsFilter implements GlobalFilter, Ordered {

    private static final String COUNT_START_TIME = "countStartTime" ;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(COUNT_START_TIME, DateUtil.currentSeconds()) ;
        return chain.filter(exchange).then(
                Mono.fromRunnable(()->{
                    Long startTime = exchange.getAttribute(COUNT_START_TIME);
                    Long endTime = DateUtil.currentSeconds() - startTime ;
                    if (startTime != null){
                        log.info(exchange.getRequest().getURI().getRawPath()+":{}",endTime);
                    }
                })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
